<template>
  <div class="person-list-drawer">
    <!-- 搜索表单 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="身份证号">
        <el-input clearable v-model="queryParams.idcard" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="护照号码">
        <el-input clearable v-model="queryParams.passportNumber" placeholder="请输入护照号码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="personData"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="selection" width="55" :reserve-selection="true"/>
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="paperNumber" label="证件号码" width="180" />

      <!-- 证件类型列 -->
      <el-table-column label="证件类型" width="180" align="center">
        <template #default="{ row }">
          <div class="id-type-container">
            <el-tooltip
              :content="row.foreigner === 1 ? '护照' : '身份证'"
              placement="top"
            >
              <component
                :is="row.foreigner === 1 ? PassportIcon : IdCardIcon"
                :class="row.foreigner === 1 ? 'passport-icon' : 'idcard-icon'"
                style="width: 18px; height: 18px;"
              />
            </el-tooltip>
            <span>
              {{ row.foreigner === 1 ? '护照' : '身份证' }}
            </span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="fetchPersonList"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import * as UserApi from '@/api/member/user'
import { Document, Postcard } from '@element-plus/icons-vue'
import {CasePersonRelationApi} from "@/api/member/cases";

// 图标别名
const PassportIcon = Document
const IdCardIcon = Postcard

const props = defineProps({
  caseId: {
    type: String,
    required: true
  }
})

const emits = defineEmits(['confirm', 'cancel'])

// 1. 定义类型
interface Person {
  id: number
  name: string
  paperNumber: string
  foreigner: number
  isCase: boolean
  // 其他可能需要的字段...
  remark?: string
  tagNames?: string[]
}

// 2. 使用类型
const personData = ref<Person[]>([])

const loading = ref(false)
const total = ref(0)
const selectedPersons = ref([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 15,
  name: undefined,
  idcard: undefined,
  passportNumber: undefined,
  caseId: props.caseId
})

// 获取表格ref
const tableRef = ref()

// 获取人员列表
const fetchPersonList = async () => {
  try {
    loading.value = true
    const res = await UserApi.getUserPage(queryParams)
    personData.value = res.list
    total.value = res.total

    // 等待表格渲染完成
    await nextTick()

    // 设置已关联人员的选中状态
    personData.value.forEach(row => {
      if (row.isCase) {
        // 这里需要获取表格的ref并调用toggleRowSelection
        tableRef.value?.toggleRowSelection(row, true)
      }
    })
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchPersonList()
}

const handleSelectionChange = async (selection) => {
  // 获取之前选中的和现在选中的差异
  const prevSelectedIds = new Set(selectedPersons.value.map(p => p.id))
  const currentSelectedIds = new Set(selection.map(p => p.id))

  // 找出新增的（需要创建关联）
  const toAdd = selection.filter(p => !prevSelectedIds.has(p.id))
  // 找出移除的（需要删除关联）
  const toRemove = selectedPersons.value.filter(p => !currentSelectedIds.has(p.id))

  try {
    // 处理新增关联
    if (toAdd.length > 0) {
      await CasePersonRelationApi.batchCreateCasePersonRelation({
        caseId: props.caseId,
        personIdList: toAdd.map(p => p.id)
      })
    }

    // 处理移除关联
    if (toRemove.length > 0) {
      await Promise.all(
        toRemove.map(person =>
          CasePersonRelationApi.deleteCasePersonRelation(props.caseId, person.id)
        )
      )
    }

    // 更新选中状态
    selectedPersons.value = selection

  } catch (error) {
    console.error('更新人员关联失败:', error)
    ElMessage.error('更新人员关联失败')
    // 恢复之前的选中状态
    tableRef.value?.clearSelection()
    selectedPersons.value.forEach(row => {
      tableRef.value?.toggleRowSelection(row, true)
    })
  }
}

// 添加行样式（可选）
const tableRowClassName = ({ row }) => {
  return row.isCase ? 'is-case-row' : ''
}

// 初始化加载
onMounted(fetchPersonList)
</script>

<style scoped>
.person-list-drawer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 搜索表单样式 */
.search-form {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.drawer-footer {
  margin-bottom: 15px;
  text-align: right;
  padding-top: 12px;
  border-top: 1px solid #eee;
}

.id-type-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.passport-icon {
  color: #1890ff; /* 护照图标蓝色 */
}

.idcard-icon {
  color: #52c41a; /* 身份证图标绿色 */
}

.id-type-container .icon {
  font-size: 18px;
  transition: transform 0.3s;
}

.id-type-container .icon:hover {
  transform: scale(1.2);
}

/* 为内联表单的表单项添加右侧间距 */
:deep(.el-form--inline .el-form-item) {
  margin-right: 16px !important;
  /* 可以根据需要调整间距值 */
}

/* 可选：调整最后一个表单项的间距，避免右侧留出过多空间 */
:deep(.el-form--inline .el-form-item:last-child) {
  margin-right: 0 !important;
}

/* 搜索表单样式 */
.search-form {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
